Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
06-Mar-2025How
async/awaitInteracts with Threads in C#The
async/awaitmechanism in C# does not create new threads but instead utilizes asynchronous programming to avoid blocking the current thread while waiting for an operation to complete.1. Key Concepts
async, which can containawaitstatements.async/awaitis built onTask<T>andTask.ThreadPool), where asynchronous work is scheduled.2. How
async/awaitUses ThreadsScenario 1: I/O-Bound (Non-Blocking)
Example: Reading a file asynchronously
How it works:
ReadToEndAsync()does not block the main thread. Instead, it awaits completion using OS-level async I/O.Scenario 2: CPU-Bound (Runs on ThreadPool)
Example: Performing heavy calculations asynchronously
How it works:
Task.Run()creates a new thread from the ThreadPool to executeExpensiveCalculation().await, execution resumes on the original thread (main thread).3. Threading Behavior in UI Applications (ASP.NET & WinForms/WPF)
ASP.NET Core (No Synchronization Context)
WinForms/WPF (Synchronization Context Exists)
4. Threading Behavior Summary
Task.Run)Summary
async/awaitdoes not create threads; it asynchronously waits.Task.Run()to offload work to ThreadPool threads..Result,.Wait(), orTask.Run()for async I/O.